package com.wj.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class SseNotificationController {

    private final Map<String, SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();
    private final ObjectMapper objectMapper = new ObjectMapper(); // 用于 JSON 序列化

    @GetMapping("/sse/subscribe")
    public SseEmitter subscribe(@RequestParam("userId") String userId) {
        SseEmitter sseEmitter = new SseEmitter(1800000L);
        sseEmitterMap.put(userId, sseEmitter);

        sseEmitter.onCompletion(() -> sseEmitterMap.remove(userId));
        sseEmitter.onTimeout(() -> sseEmitterMap.remove(userId));
        sseEmitter.onError((e) -> sseEmitterMap.remove(userId));

        try {
            sseEmitter.send(SseEmitter.event()
                    .name("connect")
                    .id(String.valueOf(System.currentTimeMillis()))
                    .data("SSE 连接已建立，等待通知...")
            );
        } catch (Exception e) {
            sseEmitter.completeWithError(e);
        }

        return sseEmitter;
    }

    // ✅✅✅ 新增：供其他 Controller 调用的推送方法
    public void sendMessageToUser(Long userId, String title, String content, String type) {
        String userIdStr = userId.toString(); // ✅ 转成 String！
        SseEmitter emitter = sseEmitterMap.get(userIdStr); // ✅ 查 String！
        if (emitter != null) {
            try {
                // 构造消息对象
                var message = Map.of(
                        "id", UUID.randomUUID().toString(),
                        "type", type != null ? type : "info",
                        "title", title,
                        "content", content,
                        "timestamp", System.currentTimeMillis()
                );

                // 推送 JSON 字符串
                emitter.send(SseEmitter.event()
                        .name("message") // 前端监听这个事件名
                        .data(objectMapper.writeValueAsString(message))
                );
            } catch (IOException e) {
                // 推送失败，清理连接
                emitter.completeWithError(e);
                sseEmitterMap.remove(userId);
            }
        }
    }
}
